import logging
import math
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

sample_info_router = APIRouter(prefix="/sampleInfo", tags=["样品分类管理"], dependencies=[Depends(oauth2_scheme)])


class SampleInfoSearch(PaginationBase):
    # 筛选条件
    fsiteNo: Optional[str] = Field("", description="站点编号")
    fsamplename: Optional[str] = Field("", description="样品名称(支持前缀匹配)")
    fclassstno: Optional[str] = Field("", description="分类编号")


@sample_info_router.get("/list", summary="")
def list_sample_info(search: SampleInfoSearch = Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from q_ts_sample_info where 1=1"
    if search.fsiteNo != "":
        sql = sql + " and fsite_no = :fsiteNo "
        param["fsiteNo"] = search.fsiteNo
    if search.fsamplename != "":
        sql = sql + " and fsamplename like concat('%', :fsamplename ,'%')"
        param["fsamplename"] = search.fsamplename
    if search.fclassstno != "":
        sql = sql + " and fclassstno = :fclassstno "
        param["fclassstno"] = search.fclassstno
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select fsite_no,fsampleno,fsamplename,fbarcode,fengname,fclassstno,"
    sql = sql + " fspec,funit,fdanger,fsafecard,fsamplestate,fupddate,foperator"
    sql = sql + " from q_ts_sample_info where 1=1"
    if search.fsiteNo != "":
        sql = sql + " and fsite_no = :fsiteNo "
        param["fsiteNo"] = search.fsiteNo
    if search.fsamplename != "":
        sql = sql + " and fsamplename like concat('%', :fsamplename ,'%')"
        param["fsamplename"] = search.fsamplename
    if search.fclassstno != "":
        sql = sql + " and fclassstno = :fclassstno "
        param["fclassstno"] = search.fclassstno
    sql = sql + " limit :limit offset :offset "
    param["offset"] = search.offset
    param["limit"] = search.limit
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['fsiteno'] = data[key][0]
        d1['fsampleno'] = data[key][1]
        d1['fsamplename'] = data[key][2]
        d1['fbarcode'] = data[key][3]
        d1['fengname'] = data[key][4]
        d1['fclassstno'] = data[key][5]
        d1['fspec'] = data[key][6]
        d1['funit'] = data[key][7]
        d1['fdanger'] = data[key][8]
        d1['fsafecard'] = data[key][9]
        d1['fsamplestate'] = data[key][10]
        d1['fupddate'] = data[key][11]
        d1['foperator'] = data[key][12]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": search.limit,
                 "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)
